<template>
  <section class="hero-section">
    <!-- 动态背景 -->
    <div class="particle-background">
      <div class="stars"></div>
      <div class="glow-effect"></div>
    </div>
    
    <!-- 轮播区域 -->
    <el-carousel 
      :interval="5000" 
      type="card" 
      height="500px"
      class="product-carousel"
      v-loading="loading"
      indicator-position="outside"
    >
      <el-carousel-item v-for="carousel in carouselItems" :key="carousel.id">
        <div class="carousel-content" @mouseenter="handleHover(carousel)" @mouseleave="handleLeave">
          <div class="product-info">
            <h2 class="glow-text">{{ carousel.title }}</h2>
            <p class="feature-text">{{ carousel.subTitle }}</p>
            <div class="stats" v-if="carousel.stats">
              <span v-for="(stat, index) in parseStats(carousel.stats)" :key="index" class="stat">
                <el-icon><Star /></el-icon>
                {{ stat }}
              </span>
            </div>
            <el-button 
              type="primary" 
              class="view-button"
              @click="viewDetail(carousel)"
            >
              {{ t('home.viewDetails') }}
            </el-button>
          </div>
          <div class="product-visual">
            <div 
              class="product-image"
              :class="{ 'hover': hoveredItem?.id === carousel.id }"
              :style="{
                background: `linear-gradient(45deg, ${carousel.backgroundColor || '#1677ff'}, ${adjustColor(carousel.backgroundColor || '#1677ff', 40)})`,
                borderRadius: '16px',
                padding: '30px'
              }"
            >
              <img v-if="carousel.imageUrl" :src="carousel.imageUrl" alt="产品图片" />
              <el-icon v-else size="60" color="#fff"><Lightning /></el-icon>
            </div>
            <div class="light-effect"></div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Star, ShoppingCart, Lightning, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getActiveCarousels } from '@/api/carousel'
import type { Carousel } from '@/types'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

const hoveredItem = ref<Carousel | null>(null)
const carouselItems = ref<Carousel[]>([])
const loading = ref(true)

const fetchCarouselItems = async () => {
  try {
    loading.value = true
    const data = await getActiveCarousels()
    // 对走马灯数据进行排序
    carouselItems.value = data.sort((a, b) => a.order - b.order)
  } catch (error) {
    console.error('获取走马灯数据失败:', error)
    ElMessage.error(t('common.fetchError'))
    // 加载失败时使用默认数据
    carouselItems.value = getDefaultCarouselItems()
  } finally {
    loading.value = false
  }
}

const parseStats = (stats: string | undefined): string[] => {
  if (!stats) return []
  return stats.split(',').map(stat => stat.trim())
}

const getDefaultCarouselItems = (): Carousel[] => {
  return [
    {
      id: 1,
      title: t('products.smartPanel'),
      subTitle: t('products.smartPanelFeature'),
      description: t('products.smartPanelDesc'),
      backgroundColor: '#1677ff',
      stats: '4.9,1200+',
      status: 'active',
      order: 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    },
    {
      id: 2,
      title: t('products.outdoorLight'),
      subTitle: t('products.outdoorLightFeature'),
      description: t('products.outdoorLightDesc'),
      backgroundColor: '#52c41a',
      stats: '4.8,800+',
      status: 'active',
      order: 2,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    },
    {
      id: 3,
      title: t('products.ceilingLight'),
      subTitle: t('products.ceilingLightFeature'),
      description: t('products.ceilingLightDesc'),
      backgroundColor: '#ff4d4f',
      stats: '4.7,1500+',
      status: 'active',
      order: 3,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
  ]
}

const handleHover = (item: Carousel) => {
  hoveredItem.value = item
}

const handleLeave = () => {
  hoveredItem.value = null
}

const viewDetail = (carousel: Carousel) => {
  if (carousel.linkUrl) {
    // 如果有链接URL，则跳转到指定链接
    if (carousel.linkUrl.startsWith('http')) {
      window.open(carousel.linkUrl, '_blank')
    } else {
      router.push(carousel.linkUrl)
    }
  } else {
    // 没有链接时触发产品详情展示事件
    emit('view-detail', carousel)
  }
}

const emit = defineEmits<{
  (e: 'view-detail', carousel: Carousel): void
}>()

const adjustColor = (color: string, amount: number) => {
  return color.replace(/^#/, '').match(/.{2}/g)?.map(hex => {
    const value = Math.min(255, Math.max(0, parseInt(hex, 16) + amount))
    return value.toString(16).padStart(2, '0')
  }).join('') || color
}

onMounted(() => {
  fetchCarouselItems()
})
</script>

<style scoped lang="scss">
.hero-section {
  position: relative;
  height: 80vh;
  max-height: 700px;
  min-height: 500px;
  overflow: visible;
  background-color: var(--bg-color);
  padding: 20px 0;

  .particle-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;

    .stars {
      position: absolute;
      width: 100%;
      height: 100%;
      background: radial-gradient(circle at center, rgba(240, 240, 240, 0.4) 0%, rgba(250, 250, 250, 0.8) 100%);
    }

    .glow-effect {
      position: absolute;
      width: 100%;
      height: 100%;
      background: linear-gradient(45deg, rgba(22, 119, 255, 0.05), rgba(250, 173, 20, 0.05));
      filter: blur(50px);
    }
  }

  .product-carousel {
    position: relative;
    z-index: 1;
    width: 90%;
    max-width: 1400px;
    margin: 0 auto;
    
    :deep(.el-carousel__indicators) {
      bottom: -30px;
      
      .el-carousel__indicator {
        .el-carousel__button {
          background-color: var(--primary-color);
          opacity: 0.3;
          border-radius: 4px;
          height: 4px;
          width: 30px;
        }
        
        &.is-active {
          .el-carousel__button {
            opacity: 1;
          }
        }
      }
    }

    :deep(.el-carousel__item) {
      background: var(--bg-color);
      border-radius: 16px;
      overflow: hidden;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      border: 1px solid var(--border-color);

      &:hover {
        transform: translateY(-5px);
        box-shadow: var(--box-shadow);
      }
    }

    .carousel-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30px;
      height: 100%;
    }

    .product-info {
      flex: 1;
      padding-right: 30px;

      .glow-text {
        font-size: 2.2rem;
        font-weight: 700;
        margin-bottom: 16px;
        color: var(--text-color);
      }

      .feature-text {
        font-size: 1.1rem;
        color: var(--text-color-secondary);
        margin-bottom: 24px;
        line-height: 1.6;
      }

      .stats {
        display: flex;
        gap: 20px;
        margin-bottom: 24px;

        .stat {
          display: flex;
          align-items: center;
          gap: 8px;
          color: var(--text-color);
          font-size: 1rem;

          .el-icon {
            color: var(--primary-color);
          }
        }
      }

      .view-button {
        padding: 10px 24px;
        font-size: 1rem;
        transition: all 0.3s ease;
        border-radius: 8px;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 15px rgba(22, 119, 255, 0.2);
        }
      }
    }

    .product-visual {
      position: relative;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      .product-image {
        max-width: 100%;
        height: auto;
        transition: all 0.4s ease;
        display: flex;
        justify-content: center;
        align-items: center;
        
        img {
          max-width: 100%;
          max-height: 250px;
          object-fit: contain;
          transition: transform 0.5s ease;
        }

        &.hover {
          transform: scale(1.05);
          
          img {
            transform: scale(1.05) rotate(3deg);
          }
        }
      }
    }
  }
}

@media (max-width: 992px) {
  .hero-section {
    height: auto;
    
    .product-carousel {
      :deep(.el-carousel__item) {
        height: auto !important;
      }
      
      .carousel-content {
        flex-direction: column;
        gap: 30px;
        
        .product-info {
          padding-right: 0;
          text-align: center;
          order: 2;
          
          .stats {
            justify-content: center;
          }
        }
        
        .product-visual {
          order: 1;
        }
      }
    }
  }
}
</style> 